package bytebuffer;

import io.Animal;
import io.AnimalHolder;

import java.lang.reflect.Constructor;
import java.util.List;

public class Decoder {

   List<Object> objectList;
   
   public Decoder() {
      AnimalHolder holder = new AnimalHolder(11, new Animal(12, 13));
      System.out.println(holder);
      Encoder encoder = new Encoder();
      objectList = encoder.encode(holder);
      createObject(holder.getClass());
      System.out.println(holder);
   }
   
   private Object createObject(Class<?> c) {
      System.out.println("Class: " + c.getSimpleName());
      Constructor<?> constructor = c.getDeclaredConstructors()[0];
      System.out.println("Constructor: " + constructor);
      Class<?>[] paramArray = constructor.getParameterTypes();
      Object[] initParams = new Object[paramArray.length];
      for (int i = 0; i < paramArray.length; i++) {
         Class param = paramArray[i];
         if (param.equals(int.class) || param.equals(Integer.class)) {
            initParams[i] = objectList.get(0);
            objectList.remove(0);
         } else {
            Object o = createObject(param);
            System.out.println("Added animal " + o);
            initParams[i] = o;
         }
      }
      try {
         System.out.println("Making new " + c.getSimpleName() + " with " + initParams + " using " + constructor);
         return constructor.newInstance(initParams);
      } catch (Exception e) {
         e.printStackTrace();
      }
      throw new RuntimeException("Creating object failed");
   }
   
}
